package com.captjack.dubbo.web.hello.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author Capt Jack
 * @date 2017/12/19
 */
@Controller
public abstract class BaseController {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

    protected final static String CONTENT_TYPE_ENCODE = "UTF-8";

    protected final static String CONTENT_TYPE_XML = "text/xml";

    protected final static String CONTENT_TYPE_HTML = "text/html";

    /**
     *
     */
    @Autowired
    private HttpServletRequest request;

    /**
     *
     */
    @Autowired
    private HttpServletResponse response;

    protected HttpServletRequest getRequest() {
        return this.request;
    }

    protected HttpServletResponse getResponse() {
        return this.response;
    }

    /**
     * 在session中set对象
     *
     * @param key   键
     * @param value 值
     */
    protected void putObjectToSession(String key, Object value) {
        try {
            this.request.getSession().setAttribute(key, value);
        } catch (Exception e) {
            LOGGER.error("put map to session failed! cause by : ", e);
        }
    }

    /**
     * 从session中获取对象
     *
     * @param key 键
     */
    protected Object getObjectFromSession(String key) {
        Object object = null;
        try {
            object = this.request.getSession().getAttribute(key);
        } catch (Exception e) {
            LOGGER.error("get object from session failed! cause by : ", e);
        }
        return object;
    }

    /**
     * 向返回流中写数据
     *
     * @param message 返回信息
     */
    protected void writeStringToResponse(String message) {
        if (message == null) {
            return;
        }
        OutputStream outputStream = null;
        try {
            this.response.setHeader("Access-Control-Allow-Origin", "*");
            this.response.setContentType("text/html; charset=utf-8");
            // 打开输出流
            outputStream = this.response.getOutputStream();
            outputStream.write(message.getBytes());
            // 刷新
            outputStream.flush();
        } catch (Exception e) {
            LOGGER.error("write data to response failed！", e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    LOGGER.error("close outputStream failed！", e);
                }
            }
        }
    }

    /***
     * 跳转页面
     * @param url   跳转地址
     */
    protected void redirectPage(String url) {
        try {
            this.response.setHeader("Access-Control-Allow-Origin", "*");
            this.response.setContentType("text/html;charset=utf-8");
            this.response.sendRedirect(url);
        } catch (Exception e) {
            LOGGER.error("redirectPage(" + url + ") is error", e);
        }
    }

    /**
     * 写文件工具
     *
     * @param filePath      文件路径
     * @param multipartFile 文件内容
     * @return 是否成功
     */
    protected boolean writeFile(String filePath, MultipartFile multipartFile) {
        // 判空
        if (filePath == null || multipartFile == null || filePath.length() == 0 || multipartFile.getSize() == 0) {
            LOGGER.error("filePath or multipartFile is null！");
            return false;
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File file = new File(filePath);
            if (!file.exists() && !file.createNewFile()) {
                LOGGER.error("File is not exists and try to create a new file failed! filePath : " + filePath);
                return false;
            }
            inputStream = multipartFile.getInputStream();
            outputStream = new FileOutputStream(file);
            int temp = inputStream.read();
            while (temp != -1) {
                outputStream.write(temp);
                temp = inputStream.read();
            }
            return true;
        } catch (IOException e) {
            LOGGER.error("Write file failed cause by : ", e);
            return false;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("Close stream failed cause by : ", e);
            }
        }
    }

    /**
     * 获取UUID字符串
     *
     * @return UUID
     */
    protected String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 我是一个抽象的
     */
    protected abstract void service();

}
